package com.jokerpan.project.filter;

import com.alibaba.fastjson.JSON;
import com.jokerpan.project.Message.Msg;
import com.jokerpan.project.util.JwtUtils;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class JWTAuthorizationFilter extends BasicAuthenticationFilter {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    public JWTAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        String tokenHeader = request.getHeader(JwtUtils.TOKEN_HEADER);
        // 如果请求头中没有Bearer信息则直接放行了
        if (tokenHeader == null || !tokenHeader.startsWith(JwtUtils.TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }
        // 如果请求头中有token，则进行解析，并且设置认证信息
        try {
            SecurityContextHolder.getContext().setAuthentication(getAuthentication(tokenHeader));
            super.doFilterInternal(request, response, chain);
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof io.jsonwebtoken.ExpiredJwtException){
                if (request.getRequestURL().indexOf("/users/clearUser") > -1){
                    super.doFilterInternal(request, response, chain);
                }else {
                    Msg result = Msg.fail("登录信息已过期，请重新登录！");
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(JSON.toJSONString(result));
                }
            }else {
                super.doFilterInternal(request, response, chain);
            }
        }
    }

    // 这里从token中获取用户信息并新建一个token 就是上面说的设置认证信息
    private UsernamePasswordAuthenticationToken getAuthentication(String tokenHeader) throws Exception {

        String token = tokenHeader.replace(JwtUtils.TOKEN_PREFIX, "");

        // 检测token是否过期 如果过期会自动抛出错误
        JwtUtils.isExpiration(token);
        String username = JwtUtils.getUsername(token);
        String role = JwtUtils.getUserRole(token);
        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        String[] permissions = role.split(",");
        for (int i = 0; i < permissions.length; i++){
            grantedAuthorities.add(new SimpleGrantedAuthority(permissions[i]));
        }
        if (username != null) {
            return new UsernamePasswordAuthenticationToken(username, null,
                    grantedAuthorities
//                    Collections.singleton(grantedAuthorities)
            );
        }
        return null;
    }

}
